import Vue from 'vue'
import VueRouter from 'vue-router'
import { TK, R_TK, getUid, getToken, removeToken } from "common/const.js";
import { postCheckToken } from "network/login.js";
const Home = () => import('views/home/Home')
const Category = () => import('views/category/Category')
const ShopCart = () => import('views/shopcart/ShopCart')
const Profile = () => import('views/profile/Profile')
const Detail = () => import('views/detail/Detail')
const Login = () => import('views/Login/Login')
//1.安装插件
Vue.use(VueRouter)
//2.创建路由对象
const routes = [
  {
    path: '',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/category',
    component: Category
  },
  {
    path: '/detail/:iid',
    component: Detail
  },
  {
    path: '/shopcart',
    component: ShopCart
  },
  // {
  //   path: '/profile',
  //   name: 'profile',
  //   beforeEnter(to,from,next) {
  //     let uid = getUid()
  //     if(uid) {
  //       next('/profile/+uid')
  //     }
  //     else {
  //       next('/login')
  //     }
  //   }
  // },
  {
    path: '/profile',
    component: Profile
  },
  {
    path: '/login',
    component: Login
  }
]
const router = new VueRouter({
  routes,
  mode: 'history'
})

export default router

function routerCheckToken(token, next) {
  postCheckToken(token)
    .then(res => {
      //3. 长期token过期 或 没有长期token且过期了
      if (res.isExpire == true) {
        console.log("重新登录");
        removeToken();
        next("/login");
      } else {
        //有newToken表示这是一个 长期token
        if (res.newToken != "") {
          localStorage.setItem(TK, res.newToken);
        } else {
          console.log("短期token没过期");
        }
        next();
      }
    })
    .catch(err => {
      console.log(err);
    });
}
